package top.kaoshanji.p1ch07a;

import org.apache.hc.core5.http.ContentType;
import top.kaoshanji.p1ch07a.listener.CustomBindingListener;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch07a-236页a：跟踪会话绑定事件
 * URL访问地址：/sessionBindings
 * @author kaoshanji
 * ^_^
 * create time 2025/4/5 10:48
 */
public class SessionBindings extends HttpServlet {

    // 会话属性
    private static final String SESSION_ATTRIBUTE_BINDINGS_LISTENER = "bindings.listener";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_PLAIN.toString());
        PrintWriter out = resp.getWriter();

        // 取得当前会话对象，必要时生成一个
        HttpSession session = req.getSession();
        // 设置新的超时
        session.setMaxInactiveInterval(3 * 60); // 3分钟

        // 增加一个 CustomBindingListener
        session.setAttribute(SESSION_ATTRIBUTE_BINDINGS_LISTENER, new CustomBindingListener(getServletContext()));

        out.println("This page intentionally left blank");
    }

}
